/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-09-29
*/
package com.rzico.order.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.service.PointService;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.Member;
import com.rzico.basics.mapper.MemberMapper;
import com.rzico.core.entity.SysUser;
import com.rzico.core.mapper.SysUserMapper;
import com.rzico.exception.CustomException;
import com.rzico.order.entity.*;
import com.rzico.order.mapper.BargainBuyMapper;
import com.rzico.order.mapper.BargainOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.order.mapper.BargainPeriodMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <pre>
 * 砍价期数业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class BargainPeriodService extends BaseServiceImpl<BargainPeriod, String> {

    @Autowired
    private BargainPeriodMapper bargainPeriodMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private BargainBuyMapper bargainBuyMapper;
    @Autowired
    private BargainOrderMapper bargainOrderMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PointService pointService;


    @Override
    public BaseMapper<BargainPeriod, String> getMapper() {
        return bargainPeriodMapper;
    }

    public List<BargainPeriod> getItemList(Long bargainBuyId) {
        Page<Object> startPage = PageHelper.startPage(1,20);
        Map<String,Object> params = new HashMap<>();
        params.put("bargainBuyId",bargainBuyId);
        return bargainPeriodMapper.selectList(params);

    }


    public BargainPeriod findByOrderId(Long orderId) {
        Map<String,Object> params = new HashMap<>();
        params.put("orderId",orderId);
        List<BargainPeriod> periodList = bargainPeriodMapper.selectList(params);
        if (periodList.size()>0) {
            return periodList.get(0);
        } else {
            return null;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public int addOrderNum(Long id,Integer value) {

        Map<String, Object> params = new HashMap<>();
        params.put("id",id);
        params.put("value",value);
        bargainPeriodMapper.addOrderNum(params);

        return 1;
    }
    @Transactional(rollbackFor = Exception.class)
    public void addOrder(Long orderId) {

        Order order = orderService.selectByPrimaryKey(orderId);

        BargainBuy bargainBuy = bargainBuyMapper.selectByPrimaryKey(order.getBargainBuyId());
        bargainBuy.setPeriodNum(bargainBuy.getPeriodNum()+1);
        bargainBuyMapper.updateByPrimaryKeySelective(bargainBuy);

        BargainPeriod bargainPeriod = new BargainPeriod();

        bargainPeriod.setMemberId(order.getMemberId());
        bargainPeriod.setCreateDate(new Date());
        bargainPeriod.setBargainBuyId(order.getBargainBuyId());
        bargainPeriod.setOrderId(order.getId());
        bargainPeriod.setStatus(0);
        bargainPeriod.setBargainNum(bargainBuy.getBargainNum());
        bargainPeriod.setPeriodNum(bargainBuy.getPeriodNum());
        bargainPeriod.setOrderNum(0);

        bargainPeriod.setSn(order.getSn());
        bargainPeriod.setAddress(order.getAddress());
        bargainPeriod.setPhone(order.getPhone());
        bargainPeriod.setConsignee(order.getConsignee());
        bargainPeriod.setReceiverId(order.getReceiverId());
        bargainPeriod.setAreaId(order.getAreaId());
        bargainPeriod.setAreaName(order.getAreaName());
        bargainPeriod.setEnterpriseId(order.getEnterpriseId());

        Member member = memberMapper.selectByPrimaryKey(order.getMemberId());

        SysUser sysUser = sysUserMapper.selectByPrimaryKey(member.getUserId());
        bargainPeriod.setAvatar(sysUser.getAvatar());
        bargainPeriod.setNickname(sysUser.getNickname());

        bargainPeriodMapper.insertUseGeneratedKeys(bargainPeriod);

    }


    @Transactional(rollbackFor = Exception.class)
    public void addBargain(Long periodId,Long memberId) {

        addOrderNum(periodId,1);

        BargainPeriod bargainPeriod = bargainPeriodMapper.selectByPrimaryKey(periodId);

        if (bargainPeriod.getMemberId().equals(memberId)) {
            throw new CustomException("本人不能砍");
        }
        if (bargainPeriod.getBargainNum()<bargainPeriod.getOrderNum()) {
            throw new CustomException("已经抢完了");
        }

        if (bargainPeriod.getStatus().equals(3)) {
            throw new CustomException("订单已关闭");
        }

        Map<String,Object> params = new HashMap<>();
        params.put("periodId",periodId);
        params.put("memberId",memberId);
        Integer w = bargainOrderMapper.selectRowCount(params);
        if (w>0) {
            throw new CustomException("您已经参与了");
        }


        if (bargainPeriod.getOrderNum()>=bargainPeriod.getBargainNum()) {
            bargainPeriod.setStatus(2);
            bargainPeriodMapper.updateByPrimaryKeySelective(bargainPeriod);
        }

        params.clear();
        params.put("periodId",periodId);
        List<BargainOrder> bargainOrderList = bargainOrderMapper.selectList(params);

        BigDecimal point = BigDecimal.ZERO;
        for (BargainOrder bargainOrder:bargainOrderList) {
            if (bargainOrder.getMemberId().equals(memberId)) {
                throw new CustomException("不能重复参与");
            }
            point = point.add(bargainOrder.getPoint());
        }

        BargainBuy bargainBuy = bargainBuyMapper.selectByPrimaryKey(bargainPeriod.getBargainBuyId());

        BigDecimal selfPoint = bargainBuy.getPoint().multiply(new BigDecimal(0.3)).setScale(0,BigDecimal.ROUND_HALF_DOWN);

        BigDecimal balance = bargainBuy.getPoint().subtract(selfPoint).
                subtract(point).subtract(new BigDecimal(bargainBuy.getBargainNum()));

        BargainOrder bargainOrder = new BargainOrder();

        bargainOrder.setMemberId(memberId);
        bargainOrder.setCreateDate(new Date());
        bargainOrder.setBargainBuyId(bargainPeriod.getBargainBuyId());
        bargainOrder.setPeriodId(periodId);
        bargainOrder.setRobot(false);
        bargainOrder.setSponsor(false);
        bargainOrder.setKing(false);
        bargainOrder.setEnterpriseId(bargainPeriod.getEnterpriseId());

        Member member = memberMapper.selectByPrimaryKey(memberId);

        SysUser sysUser = sysUserMapper.selectByPrimaryKey(member.getUserId());
        bargainOrder.setAvatar(sysUser.getAvatar());
        bargainOrder.setNickname(sysUser.getNickname());

        //记录随机金币

        if (!bargainPeriod.getStatus().equals(2)) {

            Random r = new Random();
            Integer range = balance.intValue();

            while (true) {
                int n = r.nextInt(range);
                if (n <= balance.intValue()) {
                    bargainOrder.setPoint(new BigDecimal(n).add(BigDecimal.ONE));
                    break;
                } else {
                    range = range - 1;
                    if (range < 2) {
                        bargainOrder.setPoint(BigDecimal.ONE);
                        break;
                    }
                }
            }

        } else {
            bargainOrder.setPoint(balance.add(BigDecimal.ONE));
        }


        bargainOrderMapper.insertUseGeneratedKeys(bargainOrder);

        pointService.addPoint(member.getId(), bargainOrder.getPoint().setScale(0, BigDecimal.ROUND_HALF_DOWN).longValue(), "参与砍价-领红包", 0, bargainPeriod.getOrderId());


        bargainOrderList.add(bargainOrder);

        if (bargainPeriod.getStatus().equals(2)) {
            //抢完了，出人气王
            BargainOrder maxOrder = null;
            for (BargainOrder bo:bargainOrderList) {
                if (maxOrder==null) {
                    maxOrder = bo;
                } else {
                    if (bo.getPoint().compareTo(maxOrder.getPoint())>0) {
                        maxOrder = bo;
                    }
                }
            }

            maxOrder.setKing(true);
            bargainOrderMapper.updateByPrimaryKeySelective(maxOrder);

            //插件入发起人
            bargainOrder = new BargainOrder();

            bargainOrder.setMemberId(bargainPeriod.getMemberId());
            bargainOrder.setCreateDate(new Date());
            bargainOrder.setBargainBuyId(bargainPeriod.getBargainBuyId());
            bargainOrder.setPeriodId(periodId);
            bargainOrder.setRobot(false);
            bargainOrder.setSponsor(true);
            bargainOrder.setKing(false);
            bargainOrder.setEnterpriseId(bargainPeriod.getEnterpriseId());
            bargainOrder.setAvatar(bargainPeriod.getAvatar());
            bargainOrder.setNickname(bargainPeriod.getNickname());
            bargainOrder.setPoint(selfPoint);
            bargainOrderMapper.insertUseGeneratedKeys(bargainOrder);

            pointService.addPoint(bargainPeriod.getMemberId(),selfPoint.longValue(), "砍价成功-奖红包", 0, bargainPeriod.getOrderId());

        }


    }

}
